package cc.sunwl.study.java8.流API;

import cc.sunwl.study.java8.流API.domain.Dish;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

/**
 * 并行流不一定比顺序的要快，e.g. 迭代器（依赖于上一次循环结果的）
 */
public class ParallelStreamTest {
    public static void main(String[] args) {
        // 可用内核的数量，包括超线程的虚拟内核
        int cpuCore = Runtime.getRuntime().availableProcessors();
        System.out.println("cpuCore = " + cpuCore);
        long forkJoinSum = forkJoinSum(20_000);
        System.out.println("forkJoinSum = " + forkJoinSum);
        List<Dish> list = new ArrayList<>();
        int sum1 = list.stream().map(Dish::getPrice).reduce(0, Integer::sum);
        System.out.println("sum1 = " + sum1);
        // 建议使用这个方法求和，更易读
        Integer sum2 = list.stream().mapToInt(Dish::getPrice).sum();
        //Integer sum2 = list.stream().collect(Collectors.summingInt(Dish::getPrice));
        System.out.println("sum2 = " + sum2);
    }

    private static long forkJoinSum(long n) {
        long[] numbers = LongStream.rangeClosed(1, n).toArray();
        ForkJoinTask<Long> task = new ForkJoinSumCalculator(numbers);
        return new ForkJoinPool().invoke(task);
    }
}
